#ifndef _SHARED_POINTER_HPP_
#define _SHARED_POINTER_HPP_

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

template<typename T>
struct foo
{
    int t_id;
    pthread_mutex_t t_lock;
    int t_count;
    T* t_value;
};

template<typename T>
foo<T>* foo_alloc(int id)
{
    foo<T>* fp;
    if((fp = (foo<T>*)malloc(sizeof(foo<T>)))!=NULL)
    {
        fp->t_id = id;
        fp->t_count = 1;
        if(pthread_mutex_init(&fp->t_lock,NULL)!=0)
        {
            free(fp);
            return NULL;
        }
        //剩余的初始化操作
        if((fp->t_value = (T*)malloc(sizeof(T)))==NULL)
        {
            pthread_mutex_destroy(&fp->t_lock);
            free(fp);
            return NULL;
        }
    }
    return fp;
}

template<typename T>
void foo_hold(foo<T>* fp)
{
    pthread_mutex_lock(&fp->t_lock);
    printf("Foo Origin Count is %d\n",fp->t_count);
    fp->t_count+=1;
    printf("foo pinter count add to %d\n",fp->t_count);
    pthread_mutex_unlock(&fp->t_lock);
}

template<typename T>
void foo_rele(foo<T>* fp)
{
    pthread_mutex_lock(&fp->t_lock);
    if(--fp->t_count == 0)
    {
        pthread_mutex_unlock(&fp->t_lock);
        pthread_mutex_destroy(&fp->t_lock);
        free(fp->t_value);
        free(fp);
    }else
    {
        pthread_mutex_unlock(&fp->t_lock);
    }
}

#endif //_SHARED_POINTER_HPP_
